'use strict';

webappApp.factory('photoReader', ['fileSlicer', 'JpegMeta', 'fileReaders', function(fileSlicer, JpegMeta, fileReaders) {
  return {
    read: function(file, onload, onerror) {
      var header = fileSlicer.slice(file),
          reader = fileReaders.get();
      // Only process image files.
      if (!file.type.match('image.*') && onerror) {
        onerror('File must be of type image/*');
        return;
      }
      reader.onloadend = function (e) {
        var meta;
        if (e.target.readyState === reader.DONE) {
          meta = JpegMeta.read(e.target.result);
          onload(meta);
        }
      };
      reader.onerror = function (e) {
        onerror(e);
      };
      reader.readAsBinaryString(file);
    }
  };
}])
.factory('JpegMeta', function() {
  return {
    read: function (asString) {
      return new JpegMeta.JpegFile(asString);
    }
  };
})
.factory('fileSlicer', function () {
  return {
    slice: function (file) {
      if (file.slice) {
        return file.slice(0, this.size);
      } else if (file.webkitSlice) {
        return file.webkitSlice(0, this.size);
      } else if (file.mozSlice) {
        return file.mozSlice(0, this.size);
      } else {
        return file;
      }
    },
    size: 131072
  };
});